package com.subl.component;

import com.subl.pojo.User;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
public class PrintBeans implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public Map<String, String> getBeanList() {
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        Map<String, String> map = Stream.of(beanDefinitionNames).collect(
                Collectors.toMap(k -> k,
                        k -> applicationContext.getBean(k).getClass().getName(),
                        (k1, k2) -> k1 + k2));
        return map;
    }

    public List<User> getUserList() throws SQLException {
        DataSource dataSource = (DataSource) applicationContext.getBean("DataSource#ds0");
        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("select * from tuser");
        ResultSet resultSet = preparedStatement.executeQuery();
        List<User> users = new ArrayList<>();
        while(resultSet.next()) {
            User user = new User();
            user.setId(resultSet.getLong("id"));
            user.setName(resultSet.getString("name"));
            user.setAge(resultSet.getInt("age"));
            user.setAddress(resultSet.getString("address"));
            users.add(user);
        }
        resultSet.close();
        preparedStatement.close();
        connection.close();
        return users;
    }
}
